package com.cloud.ribbon.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class RibbonDemoController {
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/ribbon")
    public String helloWorld( ){

        //第一种调用方式
        //String forObject = new RestTemplate().getForObject("http://localhost:9001/hello", String.class);

        //第二种调用方式
        //根据服务名 获取服务列表 根据算法选取某个服务 并访问某个服务的网络位置。
        ServiceInstance serviceInstance = loadBalancerClient.choose("provider");
        String forObject = new RestTemplate().getForObject("http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/hello",String.class);

        //第三种调用方式 需要restTemplate注入的方式,需再写一个类注入Bean
        //String forObject = restTemplate.getForObject("http://provider/hello", String.class);
        return forObject;
    }

}
